package server

import (
    "fmt"
    "github.com/go-kratos/kratos/v2/config"

        "go.opentelemetry.io/otel"
        "go.opentelemetry.io/otel/attribute"
        "go.opentelemetry.io/otel/exporters/jaeger"
        "go.opentelemetry.io/otel/sdk/resource"
        tracesdk "go.opentelemetry.io/otel/sdk/trace"
        semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
)

var JaegerClient struct {
  Myjaeger struct {
    CollectorUrl  string `json:"url"`
    SampleRate  float64 `json:"rate"`
    ServiceName  string `json:"service"`
    AttrKey  string `json:"attrkey"`
    AttrVal string `json:"attrval"`
  } `json:"myjaeger"`
}

func MyJaegerClient(c config.Config) {
    if err := c.Scan(&JaegerClient); err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", JaegerClient)
}

// set trace provider
func setTracerProvider(url string, rate float64, service string, attrkey string, attrval string) error {
        // Create the Jaeger exporter
        exp, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(url)))
        if err != nil {
                return err
        }
        tp := tracesdk.NewTracerProvider(
                // Set the sampling rate based on the parent span to 100%
                tracesdk.WithSampler(tracesdk.ParentBased(tracesdk.TraceIDRatioBased(rate))),
                // Always be sure to batch in production.
                tracesdk.WithBatcher(exp),
                // Record information about this application in an Resource.
                tracesdk.WithResource(resource.NewSchemaless(
                        semconv.ServiceNameKey.String(service),  // Service Tag
                        attribute.String(attrkey, attrval),
                )),
        )
        otel.SetTracerProvider(tp)
        return nil
}


func MyJaegerTraceProvider(c config.Config) {
        MyJaegerClient(c)
        err := setTracerProvider(JaegerClient.Myjaeger.CollectorUrl,
                                                        JaegerClient.Myjaeger.SampleRate,
                                                        JaegerClient.Myjaeger.ServiceName,
                                                        JaegerClient.Myjaeger.AttrKey,
                                                        JaegerClient.Myjaeger.AttrVal)
        if err != nil {
                //log.Error(err)
        }
}
